package com.kingmed.kmss.admin.modules.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingmed.kmss.admin.modules.sys.model.SysMsg;
import com.kingmed.kmss.admin.modules.sys.service.SysMsgService;
import com.kingmed.kmss.common.dto.admin.sys.MsgQueryDTO;
import com.kingmed.kmss.common.dto.admin.sys.SysMsgCreateDTO;
import com.kingmed.kmss.common.dto.admin.sys.SysMsgDTO;
import com.kingmed.kmss.common.enums.admin.MsgTypeEnum;
import com.kingmed.kmss.common.satoken.LoginHelper;
import com.kingmed.kmss.common.utils.BeanCopyUtils;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 系统消息表 前端控制器
 * </p>
 *
 * @author lilin
 * @since 2023-01-05
 */
@RestController
@RequestMapping("/sys/msg")
@Api(tags = "sys系统消息管理")
public class SysMsgController {

    @Autowired
    private SysMsgService sysMsgService;


    @ApiOperation("创建系统消息")
    @PostMapping(value = "/create")
    public CommonResponse<Boolean> create(@RequestBody @Valid SysMsgCreateDTO sysMsgDTO) {
        Integer msgType = sysMsgDTO.getMsgType();
        if (MsgTypeEnum.BUSS.getType() == msgType || MsgTypeEnum.AUDIT.getType() == msgType)
            sysMsgDTO.getReceiveById();
        SysMsg sysMsg = BeanCopyUtils.copy(sysMsgDTO, SysMsg.class);
        return CommonResponseHelper.success(sysMsgService.save(sysMsg));
    }

    @ApiOperation("批量创建系统消息")
    @PostMapping(value = "/createBatch")
    public CommonResponse<Boolean> createBatch(@RequestBody @Valid List<SysMsgCreateDTO> sysMsgList) {
        List<SysMsg> sysMsgs = BeanCopyUtils.copyList(sysMsgList, SysMsg.class);
        return CommonResponseHelper.success(sysMsgService.saveBatch(sysMsgs));
    }

    @ApiOperation("已读消息")
    @PostMapping(value = "/read")
    public CommonResponse<Boolean> read(@RequestBody @NotNull Long id) {
        SysMsg sysMsg = new SysMsg();
        sysMsg.setId(id);
        sysMsg.setMsgRead(1);
        return CommonResponseHelper.success(sysMsgService.updateById(sysMsg));
    }

    @ApiOperation("设置消息为已读-按业务条件")
    @PostMapping(value = "/markAsReadForBusiness")
    public CommonResponse<Boolean> markAsReadForBusiness(@RequestBody @Valid SysMsgDTO sysMsgDTO) {
    	sysMsgService.markAsReadForBusiness(sysMsgDTO);
        return CommonResponseHelper.success();
    }
    
    @ApiOperation("修改系统消息")
    @PostMapping(value = "/update")
    public CommonResponse<Boolean> update(@RequestBody SysMsg sysMsg) {
        return CommonResponseHelper.success(sysMsgService.saveOrUpdate(sysMsg));
    }

    @ApiOperation("删除系统消息")
    @DeleteMapping(value = "/delete/{id}")
    public CommonResponse<Boolean> removeById(@PathVariable(value = "id") Long id) {
        return CommonResponseHelper.success(sysMsgService.removeById(id));
    }

    @ApiOperation("查询系统消息列表")
    @PostMapping(value = "/list")
    public CommonResponse<List<SysMsg>> list(@RequestBody MsgQueryDTO pageDTO) {
        Long userId = LoginHelper.getUserIdByToken();
        List<SysMsg> list = sysMsgService.list(new LambdaQueryWrapper<SysMsg>()
                .eq(SysMsg::getReceiveById, userId)
                .eq(pageDTO.getMsgType() != null, SysMsg::getMsgType, pageDTO.getMsgType())
                .eq(pageDTO.getMsgRead() != null, SysMsg::getMsgRead, pageDTO.getMsgRead())
                .orderByDesc(SysMsg::getCreateTime));
        return CommonResponseHelper.success(list);
    }

    @ApiOperation("分页查询系统消息")
    @PostMapping(value = "/page")
    public CommonResponse<Page<SysMsg>> page(@RequestBody MsgQueryDTO pageDTO) {
        Long userId = LoginHelper.getUserIdByToken();
        Page<SysMsg> page = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        Page<SysMsg> pageResult = sysMsgService.page(page, new LambdaQueryWrapper<SysMsg>()
                .eq(SysMsg::getReceiveById, userId)
                .eq(pageDTO.getMsgType() != null, SysMsg::getMsgType, pageDTO.getMsgType())
                .eq(pageDTO.getMsgRead() != null, SysMsg::getMsgRead, pageDTO.getMsgRead())
                .orderByDesc(SysMsg::getCreateTime));
        return CommonResponseHelper.success(pageResult);
    }

    @ApiOperation("查询系统消息数量")
    @PostMapping(value = "/count")
    public CommonResponse<Map<Integer, Integer>> count() {
        Long userId = LoginHelper.getUserIdByToken();
        List<SysMsg> list = sysMsgService.list(new LambdaQueryWrapper<SysMsg>().eq(SysMsg::getReceiveById, userId).eq(SysMsg::getMsgRead, 0));
        Map<Integer, Integer> cntMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            Map<Integer, List<SysMsg>> map = list.stream().collect(Collectors.groupingBy(SysMsg::getMsgType));
            map.forEach((k, v) -> cntMap.put(k, (CollectionUtils.isEmpty(v) ? 0 : v.size())));
        }
        return CommonResponseHelper.success(cntMap);
    }

}
